package com.sf.tools.ui;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

import org.apache.log4j.Logger;

import com.sf.tools.common.PropertyUtil;
import com.sf.tools.common.TimerTaskUpdate;
import com.sf.tools.common.UpdateThread;
import com.sf.tools.common.Version;
import com.sf.tools.generate.SysUpdate;


public class Main extends JFrame{

	private static final Logger log = Logger.getLogger(Main.class);
	
	private static final long serialVersionUID = 1L;
	
	JTabbedPane tebPanel = new JTabbedPane();
	
	Main(){
		this.setTitle("代码生成器 V" + PropertyUtil.getKey("version") + "               当前用户："+System.getProperty("user.name"));
//		this.setBounds(200, 200, 800, 690);
		int width = 1230;
		int height = 900;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int width2 = (int) screenSize.getWidth();
		int height2 = (int) screenSize.getHeight();
		System.out.println(width + " - " + height);
		
		this.setBounds((width2-width)/2,(height2-height)/2,width, height);
		
		this.add(tebPanel);
		Image frame_icon=Toolkit.getDefaultToolkit().createImage(getClass().getResource("/flashget.png"));   
		this.setIconImage(frame_icon);
		
		JMenuBar menuBar = new JMenuBar() ;
		JMenu menuFile = new JMenu("帮助(H)") ;
		JMenuItem helpItem = new JMenuItem("About 代码生成器") ;
		menuFile.add(helpItem) ;
		menuBar.add(menuFile) ;
		this.setJMenuBar(menuBar) ;
		
		helpItem.setMnemonic('H') ;
		helpItem.setAccelerator(KeyStroke.getKeyStroke('H',java.awt.Event.ALT_MASK)) ;
		
		tebPanel.addTab("生成代码",new CodeGenerate().getCon());
		tebPanel.addTab("国际化", new Internationalization().getCon());
		tebPanel.addTab("未国际化检测", new CheckI18N().getCon());
		tebPanel.addTab("代码统计", new CodeCounter().getCon());
		tebPanel.addTab("繁简通", new Conversion().getCon());
		tebPanel.addTab("生成数据字典", new DataDictionary().getCon());
		tebPanel.addTab("颜色提取器", new ColorChooser().getCon());
		tebPanel.addTab("Json数据格式化", new JsonView().getCon());
        
		this.setResizable(false);
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		try {
			if (SystemTray.isSupported()){                             // 判断当前系统是否支持系统托盘
				Image image=Toolkit.getDefaultToolkit().createImage(getClass().getResource("/quit.png"));
				TrayIcon trayIcon=new TrayIcon(image);                 // 创建托盘图标
				trayIcon.addMouseListener(new MouseAdapter(){				// 为托盘图标添加鼠标适配器
					public void mouseClicked(MouseEvent e){
						if (e.getClickCount()==2){							// 判断是否双击了鼠标
							showFrame(true);						// 调用方法，显示窗体
						}
					}
				});
				trayIcon.setToolTip(this.getTitle());                     // 添加工具提示文本
				PopupMenu popupMenu=new PopupMenu();                      // 创建弹出菜单
				MenuItem quit = null;
				quit = new MenuItem("退出系统");
				// 创建菜单项
				quit.addActionListener(new ActionListener() {             // 为"退出"菜单项添加动作事件监听器
					public void actionPerformed(final ActionEvent arg0) {
						System.exit(0);                                   // 退出系统
					}
				});
				popupMenu.add(quit);	                                  // 为弹出菜单添加菜单项
				trayIcon.setPopupMenu(popupMenu);                         // 为托盘图标添加弹出菜弹
				SystemTray systemTray=SystemTray.getSystemTray();      	  // 获得系统托盘对象
				systemTray.add(trayIcon);                             // 为系统托盘添加托盘图标
			}
		} catch (HeadlessException e) {
			e.printStackTrace();
		} catch (AWTException e) {
			e.printStackTrace();
		}
		
		helpItem.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String msg = "该工具主要用于快速开发项目，减少重复代码编写，提高开发效率。如果您在使用过程中有任何疑问或者建议，请联系：xuyisen@sf-express.com 谢谢.";
				StringBuffer sb = new StringBuffer();
				int num = 25;
				for(int i=0;i<msg.length();i=i+num){
					sb.append(msg.substring(i, i+num<msg.length()?i+num:msg.length()));
					sb.append("\n");
				}
				JOptionPane.showMessageDialog(null, sb);
			}
		}) ;
	}
	
	public void update() {
		String updateFilePath = "D:"+File.separator+"temp"+File.separator+"generate"+File.separator+"update.jar";
		Version version = SysUpdate.getNewVersion();
		if(version != null){
			int state = JOptionPane.showConfirmDialog(null, 
					"发现新版本,是否需要更新!", "提示", JOptionPane.YES_NO_OPTION);
			if(0 == state){	//0表示选择的是确定
				showFrame(false);
				
				log.info("开始下载更新文件.");
				//下载更新文件
				ByteArrayInputStream bai = SysUpdate.InputStream(1);
				byte[] buffer = new byte[bai.available()];
				BufferedOutputStream bos = null;
				try {
					bai.read(buffer);
					File f = new File(updateFilePath);
					File f2 = new File(f.getParent());
					if(!f2.exists()){
						f2.mkdirs();
					}
					bos = new BufferedOutputStream(new FileOutputStream(new File(updateFilePath)));
					bos.write(buffer);
					bos.flush();
//					JOptionPane.showMessageDialog(new JFrame("提示"), "更新成功!");
					log.info("下载成功.");
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (bos != null) {
							bos.close();
						}
						if (bai != null) {
							bai.close();
						}
					} catch (Exception e2) {
						e2.printStackTrace();
					}
				}
				
				String currFilePath = System.getProperty("user.dir") + File.separator + "代码生成器.exe";
				UpdateThread ut = new UpdateThread(updateFilePath,currFilePath);
				ut.start();
				log.info("************1");
				System.exit(0);
				log.info("************2");
//				JOptionPane.showMessageDialog(new JFrame("提示"), "ok");
				
//				File file = new File(currFilePath);
//				file.delete();
//				
//				InputStream is;
//				try {
//					File file = new File(currFilePath);
//					if (!file.exists()) {
//					}
//					BufferedInputStream bis = new BufferedInputStream(
//							new FileInputStream(file));
//					byte[] buffer = new byte[bis.available()];
//					bis.read(buffer);
//					is = new ByteArrayInputStream(buffer);
//					bis.close();
//					if (!file.delete()) {
//						
//					}
//				} catch (FileNotFoundException e1) {
//					e1.printStackTrace();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//				
//				ByteArrayInputStream bai = SysUpdate.InputStream();
//				byte[] buffer = new byte[bai.available()];
//				BufferedOutputStream bos = null;
//				try {
//					bai.read(buffer);
//					bos = new BufferedOutputStream(new FileOutputStream(new File(currFilePath)));
//					bos.write(buffer);
//					bos.flush();
//					JOptionPane.showMessageDialog(new JFrame("提示"), "更新成功!");
//				} catch (IOException e) {
//					e.printStackTrace();
//				} finally {
//					try {
//						if (bos != null) {
//							bos.close();
//						}
//						if (bai != null) {
//							bai.close();
//						}
//					} catch (Exception e2) {
//						e2.printStackTrace();
//					}
//				}
			}
		}
		
//		JOptionPane.showMessageDialog(new JFrame("提示"), state);
	}

	/**
	 * 显示 隐藏窗体
	 */
	public void showFrame(boolean flag){
		this.setVisible(flag);                                       // 显示窗体
	}
	
	public static void start(){
		try {
//			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		EventQueue.invokeLater(new Runnable(){
			@Override
			public void run() {
				Main frame = new Main();
				frame.setVisible(true);
//				frame.update();
//				String file = Main.class.getProtectionDomain().getCodeSource().getLocation().getFile();
//				try {
//					file = URLDecoder.decode(file, "UTF-8");
//				} catch (UnsupportedEncodingException e) {
////					e.printStackTrace();
//				}
//				JOptionPane.showMessageDialog(new JFrame("提示"), file);
				
				new TimerTaskUpdate(frame);
			}
		});
	}
	
	public static void main(String[] args) {
		Main.start();
		
	}

}
